import {
  Entity,
  Column,
  ManyToMany,
  OneToMany,
  JoinTable,
  PrimaryColumn,
  BeforeInsert,
  BeforeUpdate,
} from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import * as moment from 'moment';
import { UsersEntity } from '../../user/entities/user.entity';
import { RoleEntity } from '../../role/entities/role.entity';

@Entity({ name: 'department' })
export class DepartmentEntity {
  @PrimaryColumn()
  id: string = uuidv4();

  @Column({ type: 'varchar', length: 30 })
  departmentname: string;

  @OneToMany(() => UsersEntity, (user) => user.department)
  users: UsersEntity[];

  @ManyToMany(() => RoleEntity, (role) => role.department, {
    cascade: true,
    onDelete: 'CASCADE',
  })
  @JoinTable({ name: 'department_role' })
  roles: RoleEntity[];

  @Column({ type: 'varchar', nullable: true })
  created_at: string;

  @Column({ type: 'varchar', nullable: true })
  updated_at: string;

  @BeforeInsert()
  createDates() {
    this.created_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  @BeforeUpdate()
  updateDates() {
    this.updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }
}
